<template>
  <!-- 缩进树 -->
  <div>
    <el-card>
      <el-form ref="operateForm" :model="operateForm">
        <el-row :gutter="40">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" style="padding: 0;height: 52px;">
            <el-form-item>
              <!-- <el-select v-model="operateForm.timeType" class="selector" placeholder="请选择"
                @change="selectChange(operateForm)" style="width: 26%;margin-right: 3%;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select> -->
              <!-- 按天 -->
              <el-date-picker v-if="operateForm.timeType === 'DAY'" v-model="selectDate" :picker-options="pickerOptions"
                @change="(val) => dateChange(val, { fileBytes: ['startTime', 'endTime'] }, 'operateForm')" key="tian"
                align="right" class="picker" end-placeholder="结束日期" format="yyyy-MM-dd" range-separator="至"
                start-placeholder="开始日期" type="daterange" unlink-panels value-format="yyyy-MM-dd" style="width: 100%;"
                :clearable="false">
              </el-date-picker>
              <!-- 自然周 -->
              <el-date-picker v-if="operateForm.timeType === 'WEEK'" v-model="selectDate"
                @change="(val) => dateChange(val, { fileBytes: ['startTime', 'endTime'] }, 'operateForm')" key="zhou"
                class="picker" format="yyyy 第 WW 周" placeholder="选择周" type="week" value-format="yyyy-MM-dd"
                style="width: 71%;">
              </el-date-picker>
              <!-- 自然月 -->
              <el-date-picker v-if="operateForm.timeType === 'MONTH'" v-model="selectDate"
                @change="(val) => dateChange(val, { fileBytes: ['startTime', 'endTime'] }, 'operateForm')" key="yue"
                class="picker" end-placeholder="结束月份" range-separator="至" start-placeholder="开始月份" type="monthrange"
                value-format="yyyy-MM" style="width: 71%;">
              </el-date-picker>
              <!-- 自然年 -->
              <div style="width: 71%;display: inline;">
                <el-date-picker v-if="operateForm.timeType === 'YEAR'" key="nian" v-model="operateForm.startTime"
                  class="picker pickerYear" placeholder="起始年" style="width: 31%;" type="year" value-format="yyyy">
                </el-date-picker>
                <span v-if="operateForm.timeType === 'YEAR'" class="range-word"> 至 </span>
                <el-date-picker v-if="operateForm.timeType === 'YEAR'" key="niana" v-model="operateForm.endTime"
                  class="picker pickerYear" format="yyyy" placeholder="结束年" style="width: 31%;" type="year"
                  value-format="yyyy">
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="8" :md="6" :lg="3" style="padding: 0;height: 52px;">
            <el-form-item prop="insuranceType">
              <el-select v-model="operateForm.insuranceType" placeholder="渠道" style="width: 100%;">
                <el-option v-for="dict in insurancesList" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col v-hasPermi="['customerAnalysis:clientPath:deptId']" :xs="24" :sm="8" :md="6" :lg="3"
            style="padding: 0;height: 52px;">
            <el-form-item prop="deptId">
              <!-- <treeselect v-model="operateForm.deptId" :options="manageComList" :disable-branch-nodes="true"
                :show-count="true" placeholder="请选择归属部门" /> -->
              <mechanism-cascader :deptId.sync="operateForm.deptId" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col v-hasPermi="['customerAnalysis:clientPath:sysUserId']" :xs="24" :sm="8" :md="6" :lg="3"
            style="padding: 0;height: 52px;">
            <el-form-item prop="sysUserId">
              <el-select v-model="operateForm.sysUserId" placeholder="运营人" style="width: 100%;" clearable>
                <el-option v-for="item in staffList" :key="item.dictValue" :value="item.dictValue"
                  :label="item.dictLabel" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6" :lg="3" style="padding: 0;">
            <el-form-item prop="appId">
              <el-select v-model="operateForm.appId" placeholder="平台" style="width: 100%;">
                <el-option v-for="item in terraceList" :key="item.appId" :value="item.appId" :label="item.app" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-hasPermi="['customerAnalysis:clientPath:query']" :xs="24" :sm="12" :md="7" :lg="5"
            style="padding: 0;">
            <el-form-item>
              <el-button @click="handleQuery" :loading="loading" type="primary" icon="el-icon-search">查 询</el-button>
              <el-button @click="handleReset" type="info" icon="el-icon-refresh" plain>重 置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- </el-card>
    <el-card style="margin-top: 20px;"> -->
      <!-- <div class="blood-line-box">
      <header>国联人寿公众号</header>
      <div class="blood-line-line"></div>
      <div class="blood-line-item-box">
        <span>浏览次数</span>
        <span>104</span>
      </div>
      <div class="blood-line-item-box">
        <span>平均访问时长</span>
        <span>00:01:07</span>
      </div>
      <div class="blood-line-item-box">
        <span>页面跳出率</span>
        <span>26.31%</span>
      </div>
    </div> -->
      <div style="position: relative;">
        <el-empty v-show="!dataList.id" description="暂无数据"></el-empty>
        <div id="container"></div>
      </div>
    </el-card>
  </div>
</template>
<script>
import G6 from '@antv/g6';
import { trackList, appList } from "@/api/communityOperating/customerPortrait.js";
import { mechanismCascader, SelectStaff, StaffCascader } from "@/components/index.js";
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { permission } from "@/api/communityOperating/personalSop.js";
import { parseTime } from "@/utils/common"
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
export default {
  name: 'CompactBox',
  components: {
    Treeselect, mechanismCascader,
    SelectStaff,
    StaffCascader,
  },
  data() {
    return {
      dataList: {},
      loading: false,
      graph: null,
      selectDate: '',
      operateForm: {
        timeType: 'DAY',
        dateType: 'DAY',
        startTime: '',
        deptId: null,
        sysUserId: '',
        endTime: '',
        appId: '',
      },
      options: [
        {
          value: 'DAY',
          label: '按天'
        },
        {
          value: 'WEEK',
          label: '自然周'
        },
        {
          value: 'MONTH',
          label: '自然月'
        },
        {
          value: 'YEAR',
          label: '自然年'
        }
      ],
      insurancesList: [],
      manageComList: [],
      staffList: [],
      terraceList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() || time.getTime() < (new Date().getTime() - 3600 * 1000 * 24 * 91)
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      level: 0,
    }
  },
  created() {
    this.getDicts('insurance_type').then((res) => {
      if (res.code == 200) this.insurancesList = res.data
    })
    /** 查询部门下拉树结构 */
    treeselect().then((res) => {
      if (res.code == 200) this.manageComList = res.data
    })
    this.getStaff()
  },
  mounted() {
    this.initGraph();
    // this.handleQuery()
    // app 下拉
    appList().then(res => {
      if (res.code == 200) {
        // console.log(res);
        this.terraceList = res.data;
        this.operateForm.appId = res.data[0].appId
        this.selectDate = [parseTime((new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}'),
        parseTime((new Date().getTime()), '{y}-{m}-{d}')];
        this.operateForm.startTime = this.selectDate[0]
        this.operateForm.endTime = this.selectDate[1]
        // this.handleQuery()
      } else this.$message.error(res.msg)
    })
  },
  watch: {
    level(o, v) {
      if (o != v) this.graph && this.resetGraph()
    }
  },
  methods: {
    handleQuery() {
      // console.log(checkPermi(['customerAnalysis:clientPath:deptId']), checkPermi(['customerAnalysis:clientPath:sysUserId']), !this.operateForm.sysUserId, !this.operateForm.deptId);
      if (checkPermi(['customerAnalysis:clientPath:deptId']) && checkPermi(['customerAnalysis:clientPath:sysUserId']) && !this.operateForm.sysUserId && !this.operateForm.deptId) return this.$message.error('请先选择管理机构或者运营人!')
      this.loading = true
      this.graph && this.graph.clear();
      trackList(this.operateForm).then(res => {
        if (false) {
          res.data = {
            "dataList": [
              {
                "id": "1",
                "parentId": "0",
                "name": "私域",
                "title": null,
                "visitTimes": 4,
                "visitRate": null,
                "visitDuration": null,
                "url": null,
                "referer": null,
                "visitDurationStr": "00:30",
                "children": null
              }
            ]
          }
          if (this.level > 0) {
            res.data.dataList[0].children = [
              {
                "id": "11",
                "parentId": "1",
                "name": null,
                "title": "我不懂",
                "visitTimes": 1,
                "visitRate": "25.00%",
                "visitDuration": 30092,
                "url": "https://scrm-test.guolian-life.com/h5/?code=081APw100lzaDQ1S4Y100vTQT31APw1o&state=",
                "referer": "",
                "visitDurationStr": "00:30",
                "children": null
              },
            ]
          }
          if (this.level == 2) {
            res.data.dataList[0].children[0].children = [
              {
                "id": "111",
                "parentId": "11",
                "name": null,
                "title": "我不懂1",
                "visitTimes": 1,
                "visitRate": "25.00%",
                "visitDuration": 30092,
                "url": "https://scrm-test.guolian-life.com/h5/?code=081APw100lzaDQ1S4Y100vTQT31APw1o&state=",
                "referer": "",
                "visitDurationStr": "00:30",
                "children": null
              },
            ]
          }
        }

        if (res.code == 200) {
          // console.log('res', res);
          if (res.data.dataList) {
            // console.log('this.dataList', this.dataList);
            this.level = this.getEvel(res.data.dataList).level || 0
            // console.log('this.level', this.level);
            // !this.graph && this.initGraph();
            setTimeout(() => {
              this.dataList = res.data.dataList && res.data.dataList[0] || {};
              this.graph.data(this.dataList);
              this.graph.render();
              this.graph.fitView();
            })
          }
        } else this.$message.error(res.msg)
      }).finally(() => this.loading = false)
    },

    // 获取数组深度
    getEvel(arr, level = 1) {
      // console.log('ppppp', arr);
      if (!Array.isArray(arr)) {
        return {};
      }
      let deepestArray = null;
      let deepestLevel = 0;
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        if (Array.isArray(element.children)) {
          const result = this.getEvel(element.children, level + 1);
          if (result.level > deepestLevel) {
            deepestArray = result.array;
            deepestLevel = result.level;
          }
        }
      }
      return {
        array: deepestArray || arr,
        level: deepestLevel || level
      };
    },
    getStaff() {
      // 查询执行员工
      let params = {
        name: "",
        deptId: null,
        authFlag: "Y",
      };
      permission(params).then((res) => {
        if (res.code === 200 && res.data.length) {
          res.data.forEach((item) => {
            this.staffList.push({
              dictLabel: item.userName,
              dictValue: item.userId,
            });
          });
          this.operateForm.sysUserId = this.$store.state.user.userId
        }
      });
    },
    handleReset() {
      this.selectDate = [parseTime((new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}'),
      parseTime((new Date().getTime()), '{y}-{m}-{d}')];
      this.operateForm.startTime = this.selectDate[0]
      this.operateForm.endTime = this.selectDate[1]
      this.operateForm.appId = this.terraceList[0].appId
      this.operateForm.sysUserId = ''
      this.operateForm.deptId = null
      // this.selectDate = '';
      // this.operateForm = {
      //   timeType: 'DAY',
      //   dateType: 'DAY',
      //   startTime: '',
      //   appId: '1',
      //   endTime: ''
      // }
    },
    // 日期框change事件
    selectChange(form) {
      form.selectDate = ''
      form.startTime = ''
      form.endTime = ''
    },
    // range 日期change事件
    dateChange(val, item, byte) {
      let valNew = []
      if (this.operateForm.timeType == 'WEEK') {
        valNew = [parseTime(new Date(new Date(val).getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}'),
        parseTime(new Date(new Date(val).getTime() + 5 * 24 * 60 * 60 * 1000), '{y}-{m}-{d}')]
      } else valNew = val || ["", ""];
      item.fileBytes.forEach((fileByte, index) => this.$set(this[byte], fileByte, valNew[index]));
    },
    initGraph() {
      G6.registerNode('card-node', {
        draw: (cfg, group) => {
          // console.log('cfg, group', cfg, group);
          const w = cfg.size[0];
          const h = cfg.size[1];
          const shapeDom = group.addShape('dom', {
            attrs: {
              x: -w / 2,
              y: -h / 2,
              width: w, //200,
              height: h, // 60
              // DOM's html  <span>00:01:07</span>
              // <div class="blood-line-box blue-bgc" style="width: ${200}px; height: ${100}px;">
              html: cfg.depth == 0 ? `
              <div class="blood-line-box blue-bgc" style="width: ${cfg.size[0]}px; height: ${cfg.size[1]}px;">
                    <header>${cfg.name || ''}</header>
                    <div class="blood-line-line" style="width: 80%"></div>
                    <div class="blood-line-item-box">
                      <span>浏览次数</span>
                      <span>${cfg.visitTimes || 0}</span>
                    </div>
                    <div class="blood-line-item-box">
                      <span>平均访问时长</span>
                      <span>${cfg.visitDurationStr || '00:00'}</span>
                    </div>
                    <div class="blood-line-item-box">
                      <span>访问率</span>
                      <span>${cfg.visitRate || 0}</span>
                    </div >
                  </div >
            ` : `
                  <div class="blood-line-box white-bgc" style="width: ${cfg.size[0]}px; height: ${cfg.size[1]}px;">
                    <header style="align-self: flex-start;">${cfg.title || ''}</header>
                    <div class="blood-line-line" style="width: calc(100% + 30px);background-color: #8BC1FF;"></div>
                    <div class="blood-line-item-box">
                      <span>浏览次数</span>
                      <span>${cfg.visitTimes || 0}</span>
                    </div>
                    <div class="blood-line-item-box">
                      <span>平均访问时长</span>
                      <span>${cfg.visitDurationStr || '00:00'}</span>
                    </div>
                    <div class="blood-line-item-box">
                      <span>访问率</span>
                      <span>${cfg.visitRate || 0}</span>
                    </div >
                  </div >
                  `,
            },
            // 在 G6 3.3 及之后的版本中，必须指定 name，可以是任意字符串，但需要在同一个自定义元素类型中保持唯一性
            name: 'dom-shape',
            draggable: true,
          });

          return shapeDom
        },
      });

      const container = document.getElementById('container');
      const width = container.scrollWidth
      const height = container.scrollHeight || 600;

      this.graph = new G6.TreeGraph({
        container: 'container',
        width,
        height,
        modes: {
          default: [
            {
              type: 'collapse-expand',
              onChange: function onChange(item, collapsed) {
                const data = item.getModel();
                data.collapsed = collapsed;
                return true;
              },
            },
            // 'drag-canvas',
            // 'zoom-canvas',
          ],
        },
        defaultNode: {
          type: 'card-node',
          size: [230, 120],
        },
        defaultEdge: {
          type: 'cubic-horizontal',
          style: {
            endArrow: false,
          },
        },
        layout: {
          type: 'compactBox',
          direction: 'LR',
          dropCap: true,
          indent: 20,
          getHeight: () => {
            return 100;
          },
          getHGap: function getHGap() {
            return 150;
          },
        },
        renderer: 'svg',
      });

      if (typeof window !== 'undefined')
        window.onresize = () => {
          this.resetGraph()
        };
    },
    resetGraph() {
      if (!this.graph || this.graph.get('destroyed')) return;
      if (!container || !container.scrollWidth || !container.scrollHeight) return;
      this.graph.changeSize(container.scrollWidth * (this.level / 4), container.scrollHeight);
    }
  },
}
</script>
<style lang="scss">
.white-bgc {
  background: #fff;
  color: #3694FF;
  border: 1px solid #3694FF;
}

.blue-bgc {
  background-color: #3694FF;
  color: #fff;
}

.blood-line-box {
  // width: 195px;
  // height: 115px;

  padding: 10px 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px;
  overflow: hidden;

  .blood-line-line {
    display: block;
    position: relative;
    height: 0.5px;
    background-color: #dcdfe6;

    // width: 100%;
    // width: calc(100% + 30px);
  }

  .blood-line-item-box {
    display: flex;
    justify-content: space-between;
    width: 100%;

    span {
      font-size: 12px;
    }
  }
}
</style>
